<template>
  <div class="profile-container">
    <div class="profile-content">
      <!-- 左侧头像和用户信息 -->
      <div class="user-info">
        <el-avatar 
          :size="100" 
          src="https://dnuicompanion.oss-cn-beijing.aliyuncs.com/14.png"
        />
        <div class="info-details">
          <div class="info-item">
            <span class="label">用户名：</span>
            <span class="value">{{ userInfo.username }}</span>
          </div>
          <div class="info-item">
            <span class="label">手机号：</span>
            <span class="value">{{ userInfo.phone || '暂无' }}</span>
          </div>
          <div class="info-item password-item">
            <span class="label">密码：</span>
            <span class="value">********</span>
            <el-button type="primary" size="small" @click="openPasswordDialog">修改密码</el-button>
          </div>
        </div>
      </div>

      <!-- 退出登录按钮 -->
      <div class="logout-section">
        <el-button type="danger" @click="handleLogout">退出登录</el-button>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword" :loading="loading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { updateCaregiver, getCaregiver } from '@/api/caregiver'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const passwordDialogVisible = ref(false)
const passwordFormRef = ref(null)
const loading = ref(false)
const userInfo = ref({
  userId: '',
  username: '',
  password: '',
  phone: '' // 添加手机号字段
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        console.log(userInfo)
        if (value !== userInfo.value.password) {
          callback(new Error('原密码不正确'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 3, message: '密码长度不能少于3个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const getUserInfo = async () => {
  const userStr = localStorage.getItem('user')
  if (userStr) {
    const user = JSON.parse(userStr)
    userInfo.value = {
      userId: user.userId,
      username: user.username,
      password: user.password || '',
      phone: user.phone || '' // 获取手机号
    }
    
    // 获取护工详细信息
    try {
      const caregiverInfo = await getCaregiver(user.userId)
      if (caregiverInfo) {
        userInfo.value.phone = caregiverInfo.phone || '暂无'
      }
    } catch (error) {
      console.error('获取护工详细信息失败:', error)
    }
  }
}

// 打开修改密码弹窗
const openPasswordDialog = () => {
  passwordDialogVisible.value = true
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

// 修改密码
const handleChangePassword = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    try {
      await updateCaregiver({
        caregiverId: userInfo.value.userId,
        name: userInfo.value.username,
        password: passwordForm.newPassword
      })
      
      // 更新本地存储的密码
      const userStr = localStorage.getItem('user')
      if (userStr) {
        const user = JSON.parse(userStr)
        user.password = passwordForm.newPassword
        localStorage.setItem('user', JSON.stringify(user))
        userInfo.value.password = passwordForm.newPassword
      }
      
      ElMessage.success('密码修改成功')
      passwordDialogVisible.value = false
    } catch (error) {
      console.error('密码修改失败:', error)
      ElMessage.error('密码修改失败，请重试')
    } finally {
      loading.value = false
    }
  })
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 清除本地存储的用户信息
    localStorage.removeItem('user')
    // 跳转到登录页
    router.push('/login')
    ElMessage.success('退出成功')
  }).catch(() => {})
}

onMounted(() => {
  getUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  min-height: calc(100vh - 100px);
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.profile-content {
  max-width: 800px;
  margin: 0 auto;
}

.user-info {
  display: flex;
  align-items: flex-start;
  gap: 40px;
  padding: 30px;
  border-bottom: 1px solid #e4e7ed;
}

.info-details {
  flex: 1;
}

.info-item {
  margin-bottom: 20px;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  width: 80px;
  color: #606266;
}

.value {
  color: #303133;
  margin-right: 20px;
}

.password-item {
  display: flex;
  align-items: center;
}

.logout-section {
  padding: 30px;
  text-align: center;
}
</style> 